package com.code.telegram.services.impl;

import com.code.consts.CommonConsts;
import com.code.enums.RewardKeyEnum;
import com.code.models.robot.AgentReceiveIncome;
import com.code.models.robot.RobotTaskCheck;
import com.code.models.robot.RobotTaskCheckContent;
import com.code.telegram.daos.task.AgentReceiveIncomeMapper;
import com.code.telegram.daos.task.CheckFailureMapper;
import com.code.telegram.daos.task.RobotTaskCheckContentMapper;
import com.code.telegram.daos.task.RobotTaskCheckMapper;
import com.code.telegram.managers.HttpManager;
import com.code.telegram.models.ChatMemberGroup;
import com.code.telegram.services.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 机器人任务审核服务实现类
 *
 * @author xiaoyaowang
 */
@Service
public class RobotTaskCheckServiceImpl implements RobotTaskCheckService {

    @Value("${access.chain}")
    private Integer accessChain;

    @Resource
    RobotTaskCheckMapper robotTaskCheckMapper;

    @Resource
    AgentReceiveIncomeMapper agentReceiveIncomeMapper;

    @Resource
    CheckFailureMapper checkFailureMapper;

    @Resource
    RobotTaskCheckContentMapper robotTaskCheckContentMapper;

    @Resource
    RobotSystemService robotSystemService;

    @Resource
    RobotInviteService robotInviteService;

    @Resource
    VerifiedAddrService verifiedAddrService;

    @Resource
    ChatMemberGroupService chatMemberGroupService;

    @Resource
    RequestWalletService requestWalletService;

    @Resource
    @Lazy
    HttpManager httpManager;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public int insertRobotTaskCheck(RobotTaskCheck robotTaskCheck) {
        RobotTaskCheck robotTaskCheckForDb = robotTaskCheckMapper.getRobotTaskCheckByCondition(robotTaskCheck);
        Integer taskCheckId;
        int count = 0;
        String chatId = robotTaskCheck.getChatId();
        String userName = robotTaskCheck.getUserName();
        String firstName = robotTaskCheck.getFirstName();
        String lastName = robotTaskCheck.getLastName();
        ChatMemberGroup chatMemberGroup = chatMemberGroupService.getChatMemberGroupByChatId(chatId);
        if (null != chatMemberGroup) {
            if (StringUtils.isBlank(userName)) {
                robotTaskCheck.setUserName(chatMemberGroup.getUserName());
            }
            if (StringUtils.isBlank(firstName)) {
                robotTaskCheck.setFirstName(chatMemberGroup.getFirstName());
            }
            if (StringUtils.isBlank(lastName)) {
                robotTaskCheck.setLastName(chatMemberGroup.getLastName());
            }
        }
        if (null == robotTaskCheckForDb) {
            robotTaskCheck.setDeleted(0);
            robotTaskCheck.setCreatedAt(new Date());
            robotTaskCheck.setUpdatedAt(new Date());
            robotTaskCheck.setAgentState(0);
            Integer state = robotTaskCheck.getState();
            if (state != 3) {
                robotTaskCheck.setState(0);
            }
            count = robotTaskCheckMapper.insert(robotTaskCheck);
            robotTaskCheckForDb = robotTaskCheckMapper.getRobotTaskCheckByCondition(robotTaskCheck);
        } else {
            robotTaskCheck.setId(robotTaskCheckForDb.getId());
            robotTaskCheck.setUpdatedAt(new Date());
            robotTaskCheckMapper.updateByPrimaryKeySelective(robotTaskCheck);
        }
        String picUrl = robotTaskCheck.getPicUrl();
        if (!StringUtils.isBlank(picUrl)) {
            taskCheckId = robotTaskCheckForDb.getId();
            if (null == robotTaskCheckContentMapper.getRobotTaskCheckContentCount(taskCheckId, picUrl)) {
                RobotTaskCheckContent robotTaskCheckContent = new RobotTaskCheckContent();
                robotTaskCheckContent.setPicUrl(picUrl);
                robotTaskCheckContent.setTaskCheckId(taskCheckId);
                robotTaskCheckContent.setSendText(robotTaskCheck.getSendText());
                robotTaskCheckContent.setDeleted(0);
                robotTaskCheckContent.setCreatedAt(new Date());
                robotTaskCheckContent.setUpdatedAt(new Date());
                count += robotTaskCheckContentMapper.insert(robotTaskCheckContent);
            }
        }
        return count;
    }

    @Override
    public boolean whetherCheckFailure(String chatId) {
        return null != checkFailureMapper.whetherCheckFailure(chatId);
    }

    @Override
    public boolean whetherFinishSendCheckPhoto(String chatId) {
        String value = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.PHOTO_DOWN_LIMIT.name());
        if (StringUtils.isBlank(value)) {
            value = "4";
        }
        return robotTaskCheckContentMapper.getRobotTaskCheckContentCountByChatId(chatId) >= Integer.parseInt(value);
    }

    @Override
    public boolean whetherBanedByChatId(String chatId) {
        return null != robotTaskCheckMapper.getBanTaskCheckByChatId(chatId);
    }

    @Override
    public int getUsableReceiveReward(String chatId) {
        // 获取邀请人数
        int invitedPersonCount = robotInviteService.getInvitePersonsByChatId(chatId, 0);
        // 获取总TP收益和未领取的TP数
        int tpTotalIncome = 0;
        if (invitedPersonCount >= 1 && invitedPersonCount <= 10) {
            // 1-10人  每人70TP
            tpTotalIncome = invitedPersonCount * 70;
        }
        if (invitedPersonCount >= 11 && invitedPersonCount <= 30) {
            // 11-30人  每人180TP
            tpTotalIncome = 700 + invitedPersonCount * 180;
        }
        if (invitedPersonCount >= 31 && invitedPersonCount <= 50) {
            // 31-50人  每人300TP
            tpTotalIncome = 700 + 3600 + invitedPersonCount * 300;
        }
        if (invitedPersonCount >= 51) {
            // 50人以上 每人600TP
            tpTotalIncome = 700 + 3600 + 6000 + invitedPersonCount * 600;
        }
        // 获取已领取的收益
//        Integer receivedTpAmount = robotTaskCheckMapper.getReceivedTpAmountByChatId(chatId);
//        if (null == receivedTpAmount) {
//            receivedTpAmount = 0;
//        }
        // 未领取收益
//        int unReceiveIncome = 0;
//        if (tpTotalIncome > receivedTpAmount) {
//            unReceiveIncome = tpTotalIncome - receivedTpAmount;
//        }
        return tpTotalIncome;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public void receiveIncome(String chatId) {
        Integer agentState = robotTaskCheckMapper.getAgentStateByChatId(chatId);
        if (agentState == 1) {
            int unReceiveIncome = getUsableReceiveReward(chatId);
            if (unReceiveIncome > 0) {
                String walletAddr = verifiedAddrService.getCoinAddrByChatId(chatId);
                if (StringUtils.isNotBlank(walletAddr)) {
                    AgentReceiveIncome agentReceiveIncome = new AgentReceiveIncome();
                    agentReceiveIncome.setChatId(chatId);
                    Integer robotTaskCheckId = robotTaskCheckMapper.getRobotTaskCheckIdByChatId(chatId);
                    if (null == robotTaskCheckId) {
                        robotTaskCheckId = 0;
                    }
                    agentReceiveIncome.setRobotTaskCheckId(robotTaskCheckId);
                    agentReceiveIncome.setReceiveIncome(unReceiveIncome);
                    agentReceiveIncome.setDeleted(0);
                    agentReceiveIncome.setCreatedAt(new Date());
                    agentReceiveIncome.setUpdatedAt(new Date());
                    int count = agentReceiveIncomeMapper.insert(agentReceiveIncome);
                    if (count > 0) {
                        if (accessChain == 1) {
                            requestWalletService.transferAmountToAddr(walletAddr, String.valueOf(unReceiveIncome));
                        }
                        // 当他选择领取这份TP时，奖励档位重置，及后面再邀请人奖励档位从新计算
                        List<Integer> inviteIdList = robotInviteService.getRobotInviteIdListByInviteChatId(chatId);
                        if (!CollectionUtils.isEmpty(inviteIdList)) {
                            robotInviteService.patchCancelRobotInviteRewardReset(inviteIdList);
                        }
                        // 发送领取成功的消息
                        httpManager.sendMessage(Long.parseLong(chatId), "Received successfully,please check your wallet account!");
                    } else {
                        httpManager.sendMessage(Long.parseLong(chatId), "Receive Failed,please contact the administrator!");
                    }
                }
            } else {
                httpManager.sendMessage(Long.parseLong(chatId), "Receive Failed,please contact the administrator!");
            }
        }

    }

}
